<?php

namespace App\Command;

use App\Application;
use App\ModelsHuoban\HuobanBasic;
use App\ModelsHuoban\HuobanJqrKchd;
use App\Models\Redis\RedisBasic;
use GuzzleHttp\DefaultHandler;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Yurun\Util\Swoole\Guzzle\SwooleHandler;

class SyncCommand extends Command
{
    protected static $defaultName = 'app:sync';

    protected function configure(): void
    {
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $dev = true;

        $this->setConfig();
        $swoole_config = $this->config->get('swoole.coroutine.options');

        \Swoole\Coroutine::set($swoole_config);
        $scheduler = new \Swoole\Coroutine\Scheduler;
        $scheduler->add(function () use ($dev) {
            // 启用伙伴工具包
            $this->enableHuoban();
            // 启用redis服务
            $this->enableRedis();

            $huoban_jqrkchd = new HuobanJqrKchd();
            $huoban_jqrkchd->syncHuobanKchdzt($dev);
        });

        $scheduler->start();

        return Command::SUCCESS;
    }

    public function setConfig()
    {
        $app          = new Application(dirname(__DIR__, 2));
        $config_path  = \App\ServiceProvider\Basic\ConfigServiceProvider::getConfig($app::ConfigPath());
        $this->config = new \App\ServiceProvider\Basic\ConfigService\Config($config_path);
    }

    /**
     * 启用伙伴redis
     *
     * @return void
     */
    public function enableRedis()
    {
        RedisBasic::setPool();
    }

    public function enableHuoban()
    {
        // 在你的项目入口加上这句话
        DefaultHandler::setDefaultHandler(SwooleHandler::class);

        $huoban_config = $this->config->get('huoban.huoban_pass');
        HuobanBasic::init($huoban_config);

        \Swoole\Timer::tick(3600000, function (int $timer_id) use ($huoban_config) {
            if (date('H', time()) == 23) {
                HuobanBasic::refresh($huoban_config, $timer_id);
            }
        });
    }

}
